"use client";

import { useCallback, useState } from "react";
import { Trash2, Loader2 } from "lucide-react";
import { useSearchParams } from "next/navigation";

import {
  SidebarGroup,
  SidebarGroupLabel,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  useSidebar,
} from "~/components/ui/sidebar";
import Link from "next/link";
import { useThreads } from "~/hooks/use-threads";
import { cn } from "~/lib/utils";
import { Button } from "../ui/button";

export function NavAgents() {
  const { state } = useSidebar();
  const [loadingThreadId, setLoadingThreadId] = useState<string | null>(null);
  const searchParams = useSearchParams();
  const currentThreadId = searchParams.get("threadId");
  const { threads, loading, deleteThread } = useThreads();

  const handleDeleteThread = useCallback(
    async (threadId: string) => {
      setLoadingThreadId(threadId);
      await deleteThread(threadId);
      setLoadingThreadId(null);
    },
    [deleteThread],
  );

  return (
    <SidebarGroup>
      <div className="flex items-center justify-between">
        <SidebarGroupLabel>任务</SidebarGroupLabel>
      </div>

      <SidebarMenu className="max-h-[calc(100vh-200px)] overflow-y-auto [-ms-overflow-style:'none'] [scrollbar-width:'none'] [&::-webkit-scrollbar]:hidden">
        {state !== "collapsed" && (
          <>
            {loading ? (
              // Show skeleton loaders while loading
              Array.from({ length: 3 }).map((_, index) => (
                <SidebarMenuItem key={`skeleton-${index}`}>
                  <SidebarMenuButton>
                    <div className="bg-sidebar-foreground/10 h-4 w-4 animate-pulse rounded-md"></div>
                    <div className="bg-sidebar-foreground/10 h-3 w-3/4 animate-pulse rounded"></div>
                  </SidebarMenuButton>
                </SidebarMenuItem>
              ))
            ) : threads.length > 0 ? (
              // Show all threads with project info
              <>
                {threads.map((thread, index) => {
                  // Check if this thread is currently active
                  const isActive = currentThreadId === thread.project_id;
                  const isThreadLoading = loadingThreadId === thread.project_id;

                  return (
                    <SidebarMenuItem
                      key={`thread-${thread.project_id}`}
                      className="group/row"
                    >
                      <SidebarMenuButton
                        asChild
                        className={cn("relative", {
                          "bg-accent text-accent-foreground font-medium":
                            isActive,
                        })}
                      >
                        <div className="flex w-full items-center">
                          <Link
                            href={`/agents/${thread.agent_code}?threadId=${thread.project_id}`}
                            onClick={(e) => console.log(e, thread)}
                            className="flex min-w-0 flex-1 items-center"
                          >
                            {isThreadLoading ? (
                              <Loader2 className="mr-2 h-4 w-4 flex-shrink-0 animate-spin" />
                            ) : null}
                            <span className="truncate">{thread.name}</span>
                          </Link>

                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() =>
                              handleDeleteThread(thread.project_id)
                            }
                          >
                            <Trash2 className="size-4" />
                          </Button>
                        </div>
                      </SidebarMenuButton>
                    </SidebarMenuItem>
                  );
                })}
              </>
            ) : (
              <SidebarMenuItem>
                <SidebarMenuButton className="text-sidebar-foreground/70">
                  <span>暂无任务</span>
                </SidebarMenuButton>
              </SidebarMenuItem>
            )}
          </>
        )}
      </SidebarMenu>
    </SidebarGroup>
  );
}
